package com.example.demo0331.controller;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo0331.entity.Goods;
import com.example.demo0331.entity.Shop;
import com.example.demo0331.entity.User;
import com.example.demo0331.mapper.GoodsMapper;
import com.example.demo0331.mapper.ShopMapper;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class ShopController {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @RequestMapping(value = "shop/{id}", method = RequestMethod.GET)
    public Shop get(@PathVariable int id) {
        return shopMapper.findById(id);
    }

    @GetMapping("shop")
    public List<Shop> find() {
        return shopMapper.find();
    }

    @GetMapping("shop/query")
    public IPage query(String name, int page, int size) {
        QueryWrapper<Shop> queryWrapper = null;
        if(!StringUtils.isNullOrEmpty(name)) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name", name);
        }

        Page<Shop> pParam = new Page<>(page, size);
        return shopMapper.selectPage(pParam, queryWrapper);
    }

    @PostMapping("shop")
    public Shop save(@RequestBody Shop shop) {
        shopMapper.insert(shop);
        // 因为实体类id字段加上注解@TableId，所以shop.id被赋值为新增记录的id
        return shop;
    }

    @PutMapping("shop")
    public int update(@RequestBody Shop shop) {
        return shopMapper.update(shop);
    }

    @DeleteMapping("shop/{id}")
    public int delete(@PathVariable int id) {
        return shopMapper.delete(id);
    }

    @GetMapping("shopGoods")
    public List<Shop> shopGoods() {
        return shopMapper.allWithGoods();
    }

}
